<template>
  <div class="follow-table-box">
    <ZwSearchForm row-num="3" :option="searchOption" @search="seachFun" @reset="resetForm" />
    <el-scrollbar max-height="400px" wrap-class="list-box" min-size="300px" @scroll="pageScroll">
      <div class="item-box" v-if="tableList.length">
        <div class="item" v-for="(item, index) in tableList" :key="item.follow_id">
          <div class="step-box" v-if="index <= tableList.length - 2">
            <img src="@/assets/customer/follow-icon.png" alt="" />
            <img src="@/assets/customer/follow-icon.png" alt="" />
          </div>
          <div class="time">{{ item.created_at }}</div>
          <div class="title">
            <span>{{ item.work_user_name }}</span
            >在客户为<span class="active">【{{ item.stage_name }}】</span>时添加跟进
            <span v-if="item.businessName" class="business_text">，关联商机【{{ item.businessName }}】</span>
            <el-icon v-if="item.is_edit" class="edit_icon" @click="addFollow(item)"><Edit /></el-icon>
          </div>
          <div class="content">
            {{ item?.follow_content || '' }}
            <div class="imgList" v-if="item?.follow_url.length > 0">
              <template v-for="it in item.follow_url" :key="it?.type">
                <!-- 图片 -->
                <el-image v-if="it?.type == 1" class="img" :src="it?.url" :preview-src-list="[it?.url]" :preview-teleported="true" fit="cover" />
                <!-- 文件 -->
                <el-image v-else class="img" :src="getSuffixIcon(it?.url)" @click="downFile(it?.url, it?.name)" fit="cover" />
              </template>
            </div>
          </div>
        </div>
      </div>

      <el-empty v-else image="/static/noData.png" description="暂无数据"></el-empty>
    </el-scrollbar>
    <ZWDepart ref="DepartRef" @submit="getDepart" type="1" />
    <!-- 添加跟进 -->
    <AddFollow ref="AddFollowRef" @save="seachFun" />
  </div>
</template>

<script lang="ts" setup>
  import { nextTick, ref, reactive, onMounted, computed } from 'vue'
  import ZWDepart from '@/components/ZWDepart.vue'
  import AddFollow from '../../components/AddFollow.vue'
  import { followList } from '@/api/customerCenter'
  import { getBusinessSelect } from '@/api/salesleads/salesmanagement/business'
  import { useRoute } from 'vue-router'
  import { getSuffixIcon, downFile, getSetionId, useCheckReal } from '@/utils/utils'
  import { getDay } from '@/utils/timeCycle'
  import { deepCopy } from '@/utils/helper'
  import ZwSearchForm from '@/components/zw/search-form/SearchForm'
import { barProps } from 'element-plus'

  const isReal = useCheckReal()
  const props = defineProps(['work_user_id', 'stepList', 'followType','filterTime'])
  const route = useRoute()
  const formRef = ref(null)
  let nowPageHeight = 0
  let canScroll = true
  const creators = ref([])
  const DepartRef = ref(null)
  const AddFollowRef = ref(null)
  let formData:any = reactive({
    cust_id: '',
    cust_stage_id: '',
    work_user_id: '',
    business_id: '',
    filter_time: [getDay(0), getDay(0)],
    page: 1,
    page_size: 15
  })
  const totalNum = ref(0)

  const tableList = ref([])
  const businessList = ref([])

  formData.cust_id = route.query?.id
  formData.work_user_id = props?.work_user_id

  const defaultParams = reactive({
    cust_stage_id: '',
    business_id: '',
    work_user_id: '',
    filter_time: '',
  })
  const state = reactive({
    searchParams: deepCopy(defaultParams)
  })
  const searchOption = computed(() => {
      let arr:any = []
      switch(props.followType) { 
        case 'dynamic':
          arr = [
            {
              label: '客户阶段',
              name: 'cust_stage_id',
              value: '',
              type: 'select',
              placeholder: '请选择客户阶段',
              fetchOptionApi: () => {
                return new Promise((resolve) => {
                    resolve(props.stepList)
                })
              },
              formatOption: (v: { name: any; id: any }) => ({
                label: v.name,
                value: v.id
              })
            },
            {
              label: '关联商机',
              name: 'business_id',
              value: '',
              type: 'select',
              placeholder: '请选择商机',
              fetchOptionApi: () => {
                return new Promise((resolve) => {
                    resolve(businessList.value)
                })
              },
              formatOption: (v: { name: any; business_id: any }) => ({
                label: v.name,
                value: v.business_id
              })
            },
            {
              label: '创建人',
              name: 'work_user_id',
              value: [],
              type: 'select',
              placeholder: '全部',
              popperClass: 'zw-hide_select_option',
              isUserSelect: true,
              formatOption: (v) => ({
                label: v.name,
                value: v.id
              })
           },
          ]
         break
        case 'staff' :
          arr = [
            {
              label: '客户阶段',
              name: 'cust_stage_id',
              value: '',
              type: 'select',
              placeholder: '请选择客户阶段',
              fetchOptionApi: () => {
                return new Promise((resolve) => {
                    resolve(props.stepList)
                })
              },
              formatOption: (v: { name: any; id: any }) => ({
                label: v.name,
                value: v.id
              })
            },
            {
              label: '关联商机',
              name: 'business_id',
              value: '',
              type: 'select',
              placeholder: '请选择商机',
              fetchOptionApi: () => {
                return new Promise((resolve) => {
                    resolve([...businessList.value, {name: '全部', business_id: 0}])
                })
              },
              formatOption: (v: { name: any; business_id: any }) => ({
                label: v.name,
                value: v.business_id
              })
            },
            {
              label: '时间筛选',
              name: 'filter_time',
              value: [],
              type: 'datePicker',
              datePickerType: 'daterange',
              datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
              startPlaceholder: '开始时间',
              endPlaceholder: '结束时间'
            }
          ]
        break
      }
      if(isReal) {
        const index = arr.findIndex((item:any) => item.label === '关联商机')
        arr.splice(index, 1)
      }
    return arr
  })

  // 获取跟进列表
  const followListFun = (isMore: boolean) => {
    followList(formData).then((r: any) => {
      r.data = r.data || []
      if (isMore) {
        tableList.value = [...tableList.value, ...r.data]
      } else {
        tableList.value = r.data
      }
      totalNum.value = r.total || 0
      nextTick(() => {
        canScroll = true
        nowPageHeight = document.querySelector('.item-box')?.offsetHeight || 0
      })
    })
  }
  //打开新建选择人
  const openDepart = () => {
    DepartRef.value.departVisble = true
    DepartRef.value.selectedMember = creators.value
    DepartRef.value.multiple = false
  }
  const getDepart = (res: any) => {
    creators.value = res
    console.log('creators.value: ', creators.value, getSetionId('id', creators.value)[0])
    formData.work_user_id = getSetionId('id', creators.value)[0]
  }
  // 添加跟进
  const addFollow = (val: any) => {
    const userInfo = {
      follow_id: val.follow_id,
      cust_baseinfo: {
        name: val.work_user_name
      },
      stage_id: val.stage_id,
      cust_name: val.work_user_name
    }
    AddFollowRef.value.drawerData.userInfo = userInfo
    AddFollowRef.value.drawerData.show = true
    AddFollowRef.value.followId = formData.cust_id
    // AddFollowRef.value.getFllowDetail(val.follow_id)
  }
  // 滚动加载
  const pageScroll = (e: any) => {
    if (tableList.value.length >= totalNum.value) return
    if (nowPageHeight == e.scrollTop - 186 && canScroll) {
      canScroll = false
      formData.page = formData.page + 1
      followListFun(true)
    }
  }
  const initFormData = () => {
    formData.cust_stage_id = ''
    formData.filter_time = []
    formData.page = 1
    followListFun()
  }
  const seachFun = (data?:any) => {
    if(props.filterTime){
      formData.filter_time = props.filterTime
    }

    formData.cust_stage_id = ''
    formData.work_user_id = ''
    formData.business_id = ''
    formData.page = 1
    formData.page_size = 15
    formData = {...formData, ...data}
    formData.page = 1
    followListFun()
  }
  // 清空
  const resetForm = (data:any) => {
    formData.cust_stage_id = ''
    formData.work_user_id = ''
    formData.business_id = ''
    // formData.filter_time = []
    formData.page = 1
    formData.page_size = 15
    formRef.value?.resetFields()
    followListFun()
  }
  onMounted(() => {
    getBusinessSelect({
      cust_id: route.query.id
    }).then((res: any) => {
      businessList.value = res
    })
  })
  defineExpose({
    followListFun,
    formData,
    seachFun
  })
</script>

<style lang="scss" scoped>
  .follow-table-box {
    // padding: 9px 24px 24px;
    .searchForm {
      background: #f9f9f9;
      border: 1px solid #eaeaea;
      padding: 10px;
      margin-bottom: 10px;
      .m_r {
        text-align: right;
      }
    }
    .list-box {
      .item {
        padding-left: 20px;
        margin-bottom: 26px;
        position: relative;
        .step-box {
          box-sizing: border-box;
          position: absolute;
          width: 20px;
          height: calc(100% + 42px);
          top: 0;
          left: 0;
          img {
            position: absolute;
            width: 16px;
            height: 16px;
            left: 2px;
            &:first-child {
              top: 0;
            }
            &:last-child {
              bottom: 0;
            }
          }
          &::after {
            position: absolute;
            content: '';
            width: 1;
            height: calc(100% - 36px);
            border-left: dashed 1px #ffc69e;
            top: 18px;
            left: 10px;
          }
        }
        .time {
          font-size: 12px;
          font-family: STHeitiSC-Light, STHeitiSC;
          font-weight: 300;
          color: #969696;
          margin-bottom: 16px;
        }
      }
      .time {
        font-size: 12px;
        font-family: STHeitiSC-Light, STHeitiSC;
        font-weight: 300;
        color: #969696;
        margin-bottom: 16px;
      }
      .title {
        font-size: 14px;
        font-family: STHeitiSC-Medium, STHeitiSC;
        font-weight: 500;
        color: #33302d;
        margin-bottom: 16px;
        .edit_icon {
          float: right;
          cursor: pointer;
          // margin-right:10px;
        }
        span {
          color: #0081ff;
        }
        .active {
          color: #ff6b00;
        }
        .business_text {
          color: #33302d;
        }
      }
      .content {
        background: #f9f9f9;
        border: 1px solid #eaeaea;
        padding: 16px;
        font-size: 14px;
        line-height: 18px;
        font-family: STHeitiSC-Medium, STHeitiSC;
        font-weight: 500;
        color: #33302d;
        .img {
          width: 73px;
          height: 73px;
          margin-top: 9px;
          margin-right: 10px;
        }
      }
    }
  }
  .follow_row {
    margin: -8px -10px;
    .el-col {
      margin: 8px 0;

      .el-form-item {
        margin-bottom: 0;

        .el-form-item__label-wrap {
          .el-form-item__label {
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            font-weight: 300;
            color: #33302d;
          }
        }

        :deep(.el-form-item__content) {
          width: 100%;
          .el-input,
          .el-select {
            width: 100%;
          }
          .el-range-editor {
            width: auto;
          }
        }
      }
    }
  }
</style>
